package com.daguchuangyi.erp_android.productlist.scan;

import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Vibrator;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.TextView;

import com.daguchuangyi.erp_android.R;
import com.daguchuangyi.erp_android.base.TransStatusBarActivity;
import com.daguchuangyi.erp_android.manager.NetworkManager;
import com.daguchuangyi.erp_android.manager.networkservice.ProductService;
import com.daguchuangyi.erp_android.production_detail.ProductDetailActivity;
import com.daguchuangyi.erp_android.util.ErrorHandler;
import com.daguchuangyi.erp_android.util.FileUtil;
import com.jude.utils.JUtils;

import java.util.HashMap;
import java.util.Map;

import cn.bingoogolapple.qrcode.core.QRCodeView;
import cn.bingoogolapple.qrcode.zxing.QRCodeDecoder;
import cn.bingoogolapple.qrcode.zxing.ZXingView;
import rx.Subscription;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;
import rx.subscriptions.CompositeSubscription;

/**
 * Created by lijianjian on 18/4/18.
 */

public class ScanNewActivity extends TransStatusBarActivity implements View.OnClickListener, QRCodeView.Delegate {
    private static final String TAG = "ScanNewActivity";

    private static final int REQUEST_IMAGE = 0x1;

    private TextView mGalleryTv;
    private TextView mCancelTv;
    private TextView mDoneTv;

    private ZXingView mQRCodeView;

    private CompositeSubscription mCompositeSubscription = new CompositeSubscription();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_scan_new);

        mGalleryTv = (TextView) findViewById(R.id.gallery_tv);
        mGalleryTv.setOnClickListener(this);
        mCancelTv = (TextView) findViewById(R.id.cancel_tv);
        mCancelTv.setOnClickListener(this);
        mDoneTv = (TextView) findViewById(R.id.done_tv);
        mDoneTv.setOnClickListener(this);

        mQRCodeView = (ZXingView) findViewById(R.id.zxingview);
        mQRCodeView.setDelegate(this);
//        mCaptureFragment = new CaptureFragment();
//        CodeUtils.setFragmentArgs(mCaptureFragment, R.layout.my_camera);
//        mCaptureFragment.setAnalyzeCallback(this);
//        getSupportFragmentManager().beginTransaction().replace(R.id.fl_my_container, mCaptureFragment).commit();
    }


    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.cancel_tv:
            case R.id.done_tv:
                finish();
                break;
            case R.id.gallery_tv:
                Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
                intent.addCategory(Intent.CATEGORY_OPENABLE);
                intent.setType("image/*");
                startActivityForResult(intent, REQUEST_IMAGE);
                break;
        }
    }

    @Override
    protected void onStart() {
        super.onStart();
        mQRCodeView.startCamera();
//        mQRCodeView.startCamera(Camera.CameraInfo.CAMERA_FACING_FRONT);

        mQRCodeView.startSpotAndShowRect();
    }

    @Override
    protected void onStop() {
        mQRCodeView.stopCamera();
        super.onStop();
    }

    @Override
    protected void onDestroy() {
        mQRCodeView.onDestroy();
        super.onDestroy();
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == REQUEST_IMAGE) {
            if (data != null) {
                try {
                    Uri uri = data.getData();
                    String path = FileUtil.getFilePathByUri(this, uri);
                    Log.i(TAG, "image path is : " + path);
                    String result = QRCodeDecoder.syncDecodeQRCode(path);
                    Log.i(TAG, "scan result is : " + result);
                    if (TextUtils.isEmpty(result)) {
                        JUtils.ToastLong("未找到识别码，请重试");
                    } else {
                        loadProduct(result);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
    }


    private void loadProduct(String productSerialNum) {
        Map<String, Object> queryMap = new HashMap<>();
        queryMap.put("PNO", productSerialNum);
        Subscription subscription = NetworkManager.getInstance().getRetrofit().create(ProductService.class)
                .getProductDetailByPNO(queryMap)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(productWrapper -> {
                    JUtils.Log("load product detail successfully.");
                    ProductDetailActivity.start(ScanNewActivity.this, productWrapper.getProduct().getId());
                    finish();
                }, throwable -> {
//                    Message obtain = Message.obtain();
//                    obtain.what = R.id.restart_preview;
//                    mCaptureFragment.getHandler().sendMessageDelayed(obtain, 1500);
                    ErrorHandler.handlerNetworError(throwable, "加载失败，请检查网络状态");
                    throwable.printStackTrace();
                });
        mCompositeSubscription.add(subscription);
    }

    private void vibrate() {
        Vibrator vibrator = (Vibrator) getSystemService(VIBRATOR_SERVICE);
        vibrator.vibrate(200);
    }

    @Override
    public void onScanQRCodeSuccess(String result) {
        JUtils.Log(TAG, "scan result:" + result);
        vibrate();
//        mQRCodeView.postDelayed(() -> mQRCodeView.startSpot(), 1500);
        mQRCodeView.startSpotDelay(1500);

        String[] results = result.split("\\n");
        if (results.length > 1) {
            String firstLine = result.split("\\n")[0];
            String productSerialNum = firstLine.split(":")[1];
            if (productSerialNum.contains(";")) {
                productSerialNum = productSerialNum.replace(";", " ");
            }
            JUtils.Log("product serical num is : " + productSerialNum.trim());
            loadProduct(productSerialNum.trim());
        } else {
            loadProduct(result);
        }
    }

    @Override
    public void onScanQRCodeOpenCameraError() {
        JUtils.ToastLong("打开相机出错");
    }
}
